const express = require("express");
const router = express.Router();

router.use(express.json({ limit: "50mb" })); // 支持 JSON 请求体，最大 50MB
router.use(express.urlencoded({ limit: "50mb", extended: true })); // 支持 URL 编码请求体，最大 50MB

const multer = require("multer");
const path = require("path");

let connectDAO = require("../InternalAffairsManage/connect.js");

// 设置文件存储路径和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // 文件存储目录
    cb(null, "public/xcx_file/");
  },
  filename: (req, file, cb) => {
    // 文件名：当前时间戳 + 原始文件名
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

// 初始化 multer
const upload = multer({
  storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 单个文件最大 50MB
  },
});

// 创建上传目录（如果不存在）
const fs = require("fs");
const dir = "./public/xcx_file";
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

// 文件上传路由
router.post("/upload", upload.single("file"), (req, res) => {
  console.log("req", req.file);

  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }

  // 文件信息
  const { filename, path, size, mimetype } = req.file;

  // 将文件信息存储到 MySQL 数据库
  const sql = `
    INSERT INTO Files (filename, path, size, mimetype)
    VALUES ('${filename}', '${path}', '${size}', '${mimetype}')
  `;
  connectDAO
    .queryDataBySQL(sql)
    .then(() => {
      res.send({
        code: 200,
        msg: "Success",
        file: {
          filename,
          path,
          size,
          mimetype,
        },
      });
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

module.exports = router;
